Django Passing a model through url.py to views.py

by: kinglemur, 8 years ago

Last edited: 8 years ago

In the blog tutorial I learned that you could pass a model to a general view function in urls.py. I was wondering if there was a way to pass the model through urls.py to views.py as I want to run another method in views.py that would take a parameter from an attribute from models.py (specifically link). Currently I am using "r^test/$" but I want to use "r'^(?P<pk>d+)$'" to get the specific model to pass to views.py.

My urls.py looks like:

<pre class='prettyprint lang-py'>
from django.conf.urls import url, include
from . import views
from django.views.generic import ListView, DetailView
from catalog.models import dataset

urlpatterns = [
url(r'^$', ListView.as_view(queryset=dataset.objects.all(), template_name="catalog/catalog.html")),
url(r'^Chicago/$', ListView.as_view(queryset=dataset.objects.all(), template_name="catalog/catalog.html")),
url(r'^test/$', views.results, name = 'results'),
url(r'^1$', views.resultLink, name = 'resultLink'),
]


my views.py look like:
<pre class='prettyprint lang-py'>
from django.shortcuts import render
from sodapyTry import postIt
from catalog.models import dataset
from django.views.generic import ListView, DetailView

def index(request):
return render(request, 'catalog/catalog.html')
# Create your views here.

def Chicago(request):
return render( request, 'personal/basic.html', {'content':['line one','line two']})

def results(request):
    return render( request, 'catalog/results.html', postIt("https://data.cityofchicago.org/api/views/ten5-q8vs/rows.json"))

def resultLink(request):
    return render( request, 'catalog/results.html', postIt(request.key))


and my models.py looks like
<pre class='prettyprint lang-py'>
from django.db import models
from jsonfield import JSONField

class dataset(models.Model):
    city = models.CharField(max_length=140)
    domain = models.CharField(max_length=140)
    link = models.CharField(max_length=140)
    filename = models.CharField(max_length=140)


    def __str__(self):
       return self.filename


sodapyTry.py:
<pre class='prettyprint lang-py'>
import requests
from requests.auth import HTTPDigestAuth
import json

def postIt(link):
myResponse = requests.get(link)
if(myResponse.ok):
jData = json.loads(myResponse.content)
jResults = jData["meta"]["view"]["columns"]
return {'content':jResults, 'filename':jData["meta"]["view"]["name"]}
else:
myResponse.raise_for_status()


Thanks for all the help! The Django tutorial was super helpful! Keep it up!



You must be logged in to post. Please login or register an account.